package com.ynwa;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * ArrayList和LinkedList的效率对比
 *
 * @author gzd
 * @date 2019-10-22 16:38
 */
public class ArrayListAndLinkedList {

    /**
     * 在尾部添加数据
     * 50次: A:36654, L:166372
     * 500次: A:428517, L:564653
     * 1000次: A:474900, L:706537
     * 5000次: A:888584, L:1277608 有时候接近, 偶尔L<A
     * 10000: A:1747258, L:1808315 有时候接近, 偶尔L<A
     * 50000: A:3578324, L:4510695
     * 100000: A:3624211, L:7926136
     * 500000: A:12871734, L:18065588
     * 1000000: A:39974541, L:31349085
     */
    public static void addInTail() {
        LinkedList<Integer> linkedList = new LinkedList<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
        Long start = System.nanoTime();
        for (int i = 0; i < 1000000; i++) {
            linkedList.addLast(i);

        }
        Long end = System.nanoTime();
        System.out.println("LinkedList消耗时间:" + (end - start));

        start = System.nanoTime();
        for (int i = 0; i < 1000000; i++) {
            arrayList.add(i);
        }
        end = System.nanoTime();
        System.out.println("ArrayList消耗时间:" + (end - start));
    }

    /**
     * 向头部增加元素
     * 50: A:39603458. L:32195302
     * 500: A:40432275. L:29748059
     * 5000: A:37286911. L:31639212
     * 10000: A:39847300. L:32087511
     * 100000: A:38966541. L:30461261
     */
    public static void addInHead() {
        LinkedList<Integer> linkedList = new LinkedList<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
        Long start = System.nanoTime();
        int time = 100000;
        for (int i = 0; i < time; i++) {
            linkedList.addFirst(i);
        }

        Long end = System.nanoTime();
        System.out.println("LinkedList消耗时间:" + (end - start));

        start = System.nanoTime();

        for (int i = 0; i < time; i++) {
            arrayList.add(0, i);
        }

        end = System.nanoTime();
        System.out.println("ArrayList消耗时间:" + (end - start));
    }

    public static void main(String[] argv) {
        addInTail();
    }
}
